package org.fund.framework.service.impl;

import org.fund.base_service.service.VerificationCodeService;
import org.fund.common.redis.RedisCache;
import org.fund.framework.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.concurrent.TimeUnit;

/**
 * @Author Moro
 * @Date 2022/3/12 23:42
 * @title EmailServiceImpl
 */
@Service
public class EmailServiceImpl implements EmailService {

    @Autowired
    private JavaMailSender mailSender;

    @Value("${spring.mail.username}")
    private String from;
    public static final String verifyKeyPrefix = "verifycode";
    @Autowired
    private VerificationCodeService verificationCodeService;
    @Autowired
    private RedisCache redisCache;

    @Override
    public boolean sendEmailVerificationCode(String username, String toAddress) {
        MimeMessage mimeMessage = mailSender.createMimeMessage();

        try {
            MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
//            设置发件人
            mimeMessageHelper.setFrom(from);
//            设置收件人
            mimeMessageHelper.setTo(toAddress);
//            设置邮件主题
            mimeMessageHelper.setSubject("基金管理系统注册验证码,有效时长为10分钟");
            //生成随机数
            String random = verificationCodeService.generateVerificationCode();
            //将随机数放置到redis中
            redisCache.setCacheObject(verifyKeyPrefix + username, random, 10, TimeUnit.MINUTES);

//            设置验证码的样式
            mimeMessageHelper.setText("<font style='color:green'>" + random + "</font>", true);

            mailSender.send(mimeMessage);
            return true;
        } catch (MessagingException e) {
            e.printStackTrace();
            return false;
        }
    }
}
